<?php
namespace app\api\controller;
use think\Controller;
use think\Validate;
use think\Config;
use think\Db;

class Distribution extends Controller{
    //分销模块 （包含我要提现模块）
   //分销首页
   public function myDistribution(){
      $user_id = input('post.user_id');
      if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'user_id类型错误']);}
      $map = "user_id = {$user_id}";
      $my_info = db('user')->field('name,img,time,distribut_money,unsettled_money,qrcode')->where($map)->find();
      $my_info['time'] = date("Y年m月d日 H:i",$my_info['time']);//加入时间
      // $my_info['qrcode'] = "https://".$_SERVER['HTTP_HOST'].$my_info['qrcode'];//分销二维码
      //分销佣金
      // $primary_commission = db('commissions')->where($map)->sum('commission');//一级分销佣金
      // $secondary_commission = db('commissions')->where("upper_level_id = {$user_id}")->sum('upper_level_commission');//二级分销佣金
      $my_info['commission'] = $my_info['distribut_money'] + $my_info['unsettled_money'];
      $my_info['commission_order_num'] = db('commissions')->where("upper_level_id = {$user_id} OR user_id = {$user_id}")->count();//分销订单数量
      //计算我的下级个数
      //一级用户(暂时想不到二级用户该如何做分页)二级用户是根据一级用户查到的(已加入新字段)
      $page = input('post.page');
      if($page){if(!is_numeric($page)){return json_encode(['code'=>401,'msg'=>'page参数类型错误']);}}else{$page = 0;}
      $type = input('post.type');//type 1一级用户 2二级用户
      if($type){if(!is_numeric($type)){return json_encode(['code'=>401,'msg'=>'type参数类型错误']);}}else{$type = 1;}
      $string = "user_id,name,img,time";
      if($type == 1){
          $where = "leader = {$user_id}";
      }elseif($type == 2){
          $where = "upper_level_id = {$user_id}";
      }
      $group_user = db('user')->field($string)
                              ->where($where)
                              ->order('time desc')
                              ->limit($page*10,10)
                              ->select();
      foreach($group_user as $key=>$value){
         $group_user[$key]['time'] = date("Y-m-d",$value['time']);
      }
      // $secondary_user = [];
      // foreach($primary_user as $key=>$value){
      //         $primary_user[$key]['time'] = date("Y-m-d",$value['time']);
      //         $secondary_user_info = db('user')->field($string)->where("leader = {$value['user_id']}")->order('time desc')->select();
      //         if($secondary_user_info){
      //             foreach($secondary_user_info as $k=>$vo){
      //               $secondary_user_info[$k]['time'] = date("Y-m-d",$vo['time']);
      //               $secondary_user[] = $secondary_user_info[$k];
      //             }
      //         }
      // }
      //一级用户人数
      $primary_user_num = db('user')->where("leader = {$user_id}")->count();
      // $my_info['primary_group'] = ['primary_user'=>$primary_user,'primary_user_num'=>$primary_user_num];
      //二级用户人数
      $secondary_user_num = db('user')->where("upper_level_id = {$user_id}")->count();
      // $my_info['secondary_group'] = ['secondary_user'=>$secondary_user,'secondary_user_num'=>$secondary_user_num];
      $my_info['group_num'] = $primary_user_num + $secondary_user_num;//我的团队人员个数
      return json_encode([
                       'code'=>200,
                       'msg'=>'请求成功',
                       'my_info'=>$my_info,
                       'group_user'=>$group_user,
                       'primary_user_num'=>$primary_user_num,
                       'secondary_user_num'=>$secondary_user_num
                       ]);
   }

   //分销二维码
   public function myQrcode(){
      $user_id = input('post.user_id');
      if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'user_id类型错误']);}
      $map = "user_id = {$user_id}";
      $user_qrcode = db('user')->where($map)->value('qrcode');//是否要先判断改用户二维码文件是否存在？
      if($user_qrcode){
          $user_qrcode = "https://".$_SERVER['HTTP_HOST'].'/'.$user_qrcode;
      }else{
          $wx = Db::name('wx_config')->where("config_id=1")->find();
          if($wx['date']<time()){
              $wx['access_token'] = $this->wx_acc();
          }
          $access = $wx['access_token'];
//          $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.Config::get('wechat.appid').'&secret='.Config::get('wechat.appsecret');
//          $html = file_get_contents($url);
//          $output = json_decode($html,true);
//          $access_token = $output['access_token'];
          qrcode($access,$user_id,2);
          $qrcode = 'uploads/qrcode/distribution/'.$user_id.'.png';
          db('user')->where($map)->update(['qrcode'=>$qrcode]);
          $user_qrcode = "https://".$_SERVER['HTTP_HOST'].'/'.$qrcode;
      }
      return json_encode(['code'=>200,'msg'=>'请求成功','qrcode'=>$user_qrcode]);
   }

    //获取Access_token
    function wx_acc(){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".Config::get('wechat.appid')."&secret=".Config::get('wechat.appsecret')."";
        $json = httpRequest($url);
        $json = json_decode($json,true);
        $data['access_token'] = $json['access_token'];
        $data['expires_in'] = $json['expires_in'];
        $data['date'] = time()+7200;
        db('wx_config')->where('config_id', 1)->update($data);
        return $data['access_token'];
    }
   //分销佣金
   public function myDistributionCommission(){
      $user_id = input('post.user_id');
      if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'user_id类型错误']);}
      $commission_info = db('user')->field('distribut_money,unsettled_money')->where("user_id = {$user_id}")->find();
      $commission_info['commission'] = $commission_info['distribut_money'] + $commission_info['unsettled_money'];
      $commission_goods = db('goods')->field('goods_id,name,mode,thumbnail_img,materiel_id,small,sale_type')
                                     ->where("shelves = 1")
                                     ->order(['sort desc','goods_id'])
                                     ->limit(2)
                                     ->select();
      foreach($commission_goods as $key=>$value){
            $commission_goods[$key]['price'] = $value['small'];
            if(!Validate::is($value['thumbnail_img'],'url')){
                $commission_goods[$key]['thumbnail_img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$value['thumbnail_img'];
            }
            //市场价
            $map = "goods_id = {$value['goods_id']} AND price = {$value['small']}";
            $commission_goods[$key]['market_price'] = db('spec_goods_price')->where($map)->value('market_price');
            //一级分销佣金比例
            $goods_one_proportion = db('materiel')->where("materiel_id = {$value['materiel_id']}")->value('one_proportion');
            $commission_goods[$key]['goods_commission'] = round($value['small']*$goods_one_proportion/100,2);
            unset($commission_goods[$key]['small']);
      }
      return json_encode(['code'=>200,'msg'=>'请求成功','commission_info'=>$commission_info,'commission_goods'=>$commission_goods]);
   }

   //更多分销
   public function moreDistributionGoods(){
      $page = input('post.page');
      $price = input('post.price');
      $browse_number = input('post.browse_number');
      if($page){if(!is_numeric($page)){return json_encode(array('code'=>200,'msg'=>'page类型有误'));}}else{$page = 0;}
      $where = "g.shelves = 1";
      if($price){
          if($price == 1){
              $order = 'goods_price asc';
          }else{
              $order = 'goods_price desc';
          }
      }
      if($browse_number){
          if($browse_number == 1){
              $order = 'g.browse_number asc,g.goods_id';
          }else{
              $order = 'g.browse_number desc,g.goods_id';
          }
      }
      if(!$price && !$browse_number){
           $order = 'g.sort desc,g.goods_id';
      }
      $goodsList = db('goods')->alias('g')
                              ->field('g.goods_id,g.name as goods_name,g.mode,g.thumbnail_img,g.materiel_id,g.small as goods_price,g.sale_type')
                              ->where($where)
                              ->limit($page*6,6)
                              ->order($order)
                              ->select();
      foreach($goodsList as $k=>$v){
          if($v['goods_id'] == '' || $v['goods_id'] == 'null' || $v['goods_id'] == 'undefined'){
              unset($goodsList[$k]);
          }
          if(!Validate::is($v['thumbnail_img'],'url')){
              $goodsList[$k]['thumbnail_img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$v['thumbnail_img'];
          }
          //市场价
          $map = "goods_id = {$v['goods_id']} AND price = {$v['goods_price']}";
          $goodsList[$k]['market_price'] = db('spec_goods_price')->where($map)->value('market_price');
          //一级分销佣金比例
          $goods_one_proportion = db('materiel')->where("materiel_id = {$v['materiel_id']}")->value('one_proportion');
          $goodsList[$k]['goods_commission'] = round($v['goods_price']*$goods_one_proportion/100,2);
      }
      if($goodsList){
          return json_encode(['code'=>200,'msg'=>'请求成功','commission_goods'=>$goodsList]);
      }else{
          return json_encode(['code'=>201,'msg'=>'暂无数据']);
      }
   }

   //筛选
   public function classifiedProduct(){
        $page = input('post.page');
        $label_id = input('post.label_id');
        $price = input('post.price');
        $browse_number = input('post.browse_number');
        if($page){if(!is_numeric($page)){return json_encode(array('code'=>401,'msg'=>'参数page类型有误'));}}else{$page = 0;}
        if($label_id == '' || $label_id == 'null' || $label_id == 'undefined'){
            return json_encode(array('code'=>401,'msg'=>'参数label_id缺失'));
        }
        //$map = "g.shelves = 1 AND g.sale_type = 1";
       $map = "g.shelves = 1";
        if($browse_number){
            if($browse_number == 1){
                $order = 'g.browse_number asc,g.goods_id';
            }else{
                $order = 'g.browse_number desc,g.goods_id';
            }
        }
        if($price){
            if($price == 1){
               $order = 'goods_price';
            }else{
               $order = 'goods_price desc';
            }
        }
        if(!$browse_number && !$price){
            $order = 'g.sort,g.goods_id';
        }
        if($label_id){
             if(is_string($label_id)){
                  $label_id = explode(',',$label_id);
                  $where = [];
                  foreach($label_id as $k=>$vo){
                     $where[] = "(l.label_id LIKE '{$vo},%' OR l.label_id LIKE '%,{$vo},%' OR l.label_id LIKE '%,{$vo}')";
                  }
                  $where = implode(' AND ',$where);
                  $goodsList = db('goods_label')->alias('l')
                                                ->field('g.goods_id,g.name as goods_name,g.mode,g.thumbnail_img,g.materiel_id,g.small as goods_price,g.sale_type')
                                                ->join('goods g','g.goods_id = l.goods_id','RIGHT')
                                                ->where($where)
                                                ->where($map)
                                                ->order($order)
                                                ->limit($page*6,6)
                                                ->select();
            }
            foreach($goodsList as $key=>$v){
                if(!Validate::is($v['thumbnail_img'],'url')){
                    $goodsList[$key]['thumbnail_img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$v['thumbnail_img'];
                }
                //市场价
                $map = "goods_id = {$v['goods_id']} AND price = {$v['goods_price']}";
                $goodsList[$key]['market_price'] = db('spec_goods_price')->where($map)->value('market_price');
                //一级分销佣金比例
                $goods_one_proportion = db('materiel')->where("materiel_id = {$v['materiel_id']}")->value('one_proportion');
                $goodsList[$key]['goods_commission'] = $v['goods_price']*$goods_one_proportion/100;
            }
        }
        if($goodsList){
            return json_encode(array('code'=>200,'msg'=>'请求成功','commission_goods'=>$goodsList));
        }else{
            return json_encode(array('code'=>201,'msg'=>'暂无数据'));
        }
    }

    //分销订单
   public function myDistributionOrder(){
       $user_id = input('post.user_id');
       if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'user_id类型错误']);}
       $page = input('post.page');
       if($page){if(!is_numeric($page)){return json_encode(['code'=>401,'msg'=>'page类型错误']);}}else{$page = 1;}
       $map = "upper_level_id = {$user_id} OR user_id = {$user_id}";
       $distribution_order_list = db('commissions')->where($map)->order('add_time desc')->paginate(10)->toArray();

       foreach($distribution_order_list['data'] as $key=>$value){
           if($value['type']==1){
               $comm_order = db('order')->where("order_id = {$value['order_id']} and order_status = 1 OR order_id ={$value['order_id']} and order_status = 2 OR order_id ={$value['order_id']} and order_status = 3 AND type = 2")->field('pay_price,add_time,pay_time,distribution_settlement')->find();
               $distribution_order_list['data'][$key]['distribution_settlement'] = $comm_order['distribution_settlement'];
           }elseif ($value['type']==2){
               $comm_order = db('card_order')->where("card_order_id={$value['order_id']}")->field('pay_price,add_time,pay_time')->find();
               $distribution_order_list['data'][$key]['distribution_settlement'] = 1;
           }
           $distribution_order_list['data'][$key]['pay_price'] = $comm_order['pay_price'];
            $distribution_order_list['data'][$key]['add_time'] = date('Y-m-d',$comm_order['add_time']);
            $distribution_order_list['data'][$key]['pay_time'] = date("Y-m-d",$comm_order['pay_time']);

            if($value['upper_level_id'] == $user_id){
               // $where = "user_id = {$value['upper_level_id']}";
               $distribution_order_list['data'][$key]['user_level'] = 2;
               $distribution_order_list['data'][$key]['my_commission'] = $value['upper_level_commission'];
            }elseif($value['user_id'] == $user_id){
               // $where = "user_id = {$value['user_id']}";
               $distribution_order_list['data'][$key]['user_level'] = 1;
               $distribution_order_list['data'][$key]['my_commission'] = $value['commission'];
            }
            unset($distribution_order_list['data'][$key]['upper_level_commission']);
            unset($distribution_order_list['data'][$key]['commission']);
            //下级用户信息
            $where = "user_id = {$value['suser_id']}";
            $subordinate_user_info = db('user')->field('name,img')->where($where)->find();
            $distribution_order_list['data'][$key]['user_name'] = $subordinate_user_info['name'];
            $distribution_order_list['data'][$key]['user_img'] = $subordinate_user_info['img'];
       }
       if($distribution_order_list){
          return json_encode(['code'=>200,'msg'=>'请求成功','distribution_order_list'=>$distribution_order_list]);
       }else{
          return json_encode(['code'=>201,'msg'=>'暂无数据']);
       }
   }

   //提现
   //基本信息
   public function withdrawInfo(){
      $user_id = input('post.user_id');
      if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'user_id类型错误']);}
       $list = Db::name("config")->where("type='x'")->select();
       foreach ($list as $rs){
           $config[$rs['name']] = $rs['value'];
       }
      $withdraw_info = db('user')->field('name,distribut_money')->where("user_id = {$user_id}")->find();
       $withdraw_info['money_fee'] = $config['money_fee'];
      return json_encode(['code'=>200,'msg'=>'请求成功','withdraw_info'=>$withdraw_info]);
   }

   //提现申请
   public function userWithdraw(){
      $user_id = input('post.user_id');
      if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'user_id类型错误']);}
      $map = "user_id = {$user_id}";
      $user_distribut_money = db('user')->where($map)->value('distribut_money');
      $money = input('post.money/d');
      if($money == '' || $money == 'null' || $money == 'undefined'){
         return json_encode(['code'=>401,'msg'=>'请输入提现金额']);
      }

       $list = Db::name("config")->where("type='x'")->select();
       foreach ($list as $rs){
           $config[$rs['name']] = $rs['value'];
       }

       if($money < (int)$config['money_fee']){return json_encode(['code'=>401,'msg'=>'金额达到'.$config['money_fee'].'元以上方可提现']);}
      if($money > $user_distribut_money){return json_encode(['code'=>401,'msg'=>'您的提现金额已超过可提现额度']);}
      $withdrawData = [];
       $poundage = $money*(int)$config['fee']/100;
       if($poundage<=$config['min_fee']){$poundage = $config['min_fee'];}elseif ($poundage>=$config['max_fee']){$poundage = $config['min_fee'];}
      $withdrawData['user_id'] = $user_id;
      $withdrawData['add_time'] = time();
       $withdrawData['money'] = $money;
       $withdrawData['poundage'] =$poundage;
      Db::startTrans();
      try{
        db('withdrawal')->insert($withdrawData);
        db('user')->where($map)->setDec('distribut_money',$money);
        Db::commit();
      }catch(\Exception $e){
        Db::rollback();
        return json_encode(['code'=>201,'msg'=>'提现申请失败']);
      }
      return json_encode(['code'=>200,'msg'=>'提现申请成功']);
   }

   //提现明细
   public function withdrawalDetail(){
      $user_id = input('post.user_id');
      if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'user_id类型错误']);}
      $page = input('post.page');
      if($page){if(!is_numeric($page)){return json_encode(['code'=>401,'msg'=>'page参数类型错误']);}}else{$page = 0;}
      $withdrawal_list = db('withdrawal')->field('withdrawal_id,add_time,money,state')
                                         ->where("user_id = {$user_id}")
                                         ->order('add_time desc')
                                         ->limit($page*10,10)
                                         ->select();
      foreach($withdrawal_list as $key=>$value){
        $withdrawal_list[$key]['add_time'] = date("Y-m-d H:i",$value['add_time']);
      }
      if($withdrawal_list){
         return json_encode(['code'=>200,'msg'=>'请求成功','withdrawal_list'=>$withdrawal_list]);
      }else{
         return json_encode(['code'=>201,'msg'=>'暂无数据']);
      } 
   }

   //资金明细
   public function cashDetail(){
      $withdrawal_id = input('post.withdrawal_id');
      if(!is_numeric($withdrawal_id)){return json_encode(['code'=>401,'msg'=>'withdrawal_id类型错误']);}
      $cash_info = db('withdrawal')->field('add_time,money,state,pay_serial_number,pay_time,sn')
                                   ->where("withdrawal_id = {$withdrawal_id}")
                                   ->find();

         $cash_info['add_time'] = date("Y-m-d H:i:s",$cash_info['add_time']);
         if($cash_info['state'] == 3) {
             $cash_info['pay_time'] = date("Y-m-d H:i:s", $cash_info['pay_time']);
         }
      return json_encode(['code'=>200,'msg'=>'请求成功','cash_info'=>$cash_info]);
   }   

}